package com.forcht.ioc.context;

import com.forcht.ioc.BeanDefinition;
import com.forcht.ioc.factory.AbstractBeanFactory;
import com.forcht.ioc.factory.AutowireCapableBeanFactory;
import com.forcht.ioc.io.ResourceLoader;
import com.forcht.ioc.xml.XmlBeanDefinitionReader;

import java.util.Map;

/**
 * Created by forcht on 2018/4/18.
 */
public class ClassPathXmlApplicationContext extends AbstractApplicationContext{

    private String configLocation;

    public ClassPathXmlApplicationContext(String configLocation) throws Exception {
        this(configLocation,new AutowireCapableBeanFactory());
    }
    public ClassPathXmlApplicationContext(String configLocation,AbstractBeanFactory beanFactory) throws Exception {
        super(beanFactory);
        this.configLocation=configLocation;
        refresh();
    }

    @Override
    public void refresh() throws Exception {
        XmlBeanDefinitionReader xmlBeanDefinitionReader=new XmlBeanDefinitionReader(new ResourceLoader());
        xmlBeanDefinitionReader.loadBeanDefinitions(configLocation);

        for (Map.Entry<String, BeanDefinition> beanDefinitionEntry : xmlBeanDefinitionReader.getRegistry().entrySet()) {
            beanFactory.registerBeanDefinition(beanDefinitionEntry.getKey(), beanDefinitionEntry.getValue());
        }
    }
}
